package com.sunshine.asm.oneday;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.Iterator;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;

public class MyClassFileTransformer implements ClassFileTransformer {

	public byte[] transform(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) throws IllegalClassFormatException {

		ClassReader cr = new ClassReader(classfileBuffer);
		ClassNode classNode = new ClassNode();
		cr.accept(classNode, 0);
		
		//transform 
		
		Iterator<MethodNode> is = classNode.methods.iterator();
		while(is.hasNext())
		{
			MethodNode mn = is.next();
			
			InsnList il = new InsnList();
			
			
			InsnList begin = new InsnList();
		
			AbstractInsnNode node = new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/System", "currentTimeMillils", "(V)J");
			AbstractInsnNode beginVar = new VarInsnNode(Opcodes.LSTORE,1);
			
			
			
			
			//begin.
			il.add(begin);
			
			
			
			il.add(mn.instructions);
			
			InsnList end1 = new InsnList();
			InsnList end2 = new InsnList();
			il.add(end1);
			il.add(end2);
			mn.instructions=il;
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
		}
		
		//end
		ClassWriter cw = new ClassWriter(cr, 0);
		cr.accept(classNode,0);
		return cw.toByteArray();
	}

}
